package com.hub.grpc.server.service;


import com.alibaba.fastjson2.JSONObject;
import com.hub.grpc.proto.ChatRequest;
import com.hub.grpc.proto.ChatResponse;
import com.hub.grpc.proto.ChatServiceGrpc;
import com.hub.grpc.server.annotation.GrpcService;
import com.hub.grpc.server.dao.DemoMapper;
import com.hub.grpc.server.entity.Demo;
import com.hub.grpc.server.service.msg.RabbitMQSender;
import io.grpc.stub.StreamObserver;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @ author 飞天蝙蝠
 * @ date & time 2024/12/31 8:43
 */
@Slf4j
@GrpcService
public class ChatService extends ChatServiceGrpc.ChatServiceImplBase{

    @Autowired
    private RabbitMQSender rabbitMQSender;

    @Autowired
    private DemoMapper demoMapper;

    @Override
    public StreamObserver<ChatRequest> chat(StreamObserver<ChatResponse> responseObserver) {
        return new StreamObserver<ChatRequest>() {
            @Override
            public void onNext(ChatRequest chatRequest) {
                int userId = chatRequest.getUserId();
                String msg = chatRequest.getMsg();
                log.info("[ChatService] 服务端处理开始....");
                log.info("[ChatService] 客户端说: [" + msg + "]");
                Demo demo = new Demo();
                demo.setMsg(JSONObject.toJSONString(chatRequest));
                demoMapper.insert(demo);
                rabbitMQSender.send(JSONObject.toJSONString(chatRequest));
                responseObserver.onNext(ChatResponse.newBuilder()
                        .setUserId(chatRequest.getUserId())
                        .setMsg("这是一条来自[服务端]的消息: 你好，收到了-" + userId + " 的消息. " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ssSSS").format(new Date()) + "\n")
                        .build());
            }
            @Override
            public void onError(Throwable throwable) {
                log.error("[ChatService] gRPC dealing error");
            }
            @Override
            public void onCompleted() {
                responseObserver.onCompleted();
            }
        };
    }
}
